<?php

namespace App\Admin\Service\Traits;


use App\Common\Exception\ApiMessageException;
use App\Common\Model\Model;
use App\Common\Util\ImitateAop\Attributes\Transaction;

/**
 * 通用修改存储操作
 *
 * @method void beforeWrite(&$data, $id = null)
 * @method void beforeStore(&$data)
 * @method void afterWrite()
 * @method void afterStore()
 */
trait StoreServiceTrait
{
    /**
     * @param array $data
     *
     * @return Model|null
     * @throws ApiMessageException
     */
    #[Transaction]
    public function store(array $data): ?Model
    {
        method_exists($this, 'beforeWrite') and $this->beforeWrite($data);
        method_exists($this, 'beforeStore') and $this->beforeStore($data);

        unset($data[$this->model->getPrimaryKey()]);
        $this->model->setAttrs(array_filter($data, fn($v) => !is_null($v)));
        $result = $this->model->save();

        if ($result) {
            method_exists($this, 'afterWrite') and $this->afterWrite();
            method_exists($this, 'afterStore') and $this->afterStore();
        } else {
            throw new ApiMessageException('保存失败');
        }

        return $this->model;
    }
}
